package ids.dev.converter;

import ids.dev.util.IDSStringUtil;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

import org.apache.commons.lang3.StringUtils;

@FacesConverter(value="DateConverter")
public class DateConverter implements Converter{


        @Override
        public Object getAsObject(FacesContext facesContext, UIComponent uiComponent, String value) {
        	if(IDSStringUtil.isNotEmpty(value)){
	        	Calendar cal = Calendar.getInstance();
	        	String[] values = value.split("/");
	        	cal.set(Calendar.DAY_OF_MONTH, Integer.valueOf(values[0]));
	        	cal.set(Calendar.MONTH, Integer.valueOf(values[1]) - 1);
	        	cal.set(Calendar.YEAR, Integer.valueOf(values[2]));
	        	return cal;
        	}
			return null;
        }

        @Override
        public String getAsString(FacesContext facesContext, UIComponent uiComponent, Object value) {
        	if(value == null){
        		Calendar result = (Calendar) value;
            	SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
    			return format.format(result.getTime());
        	}
        	return "";
        	
        }

}
